<script>
  let phone = "";
  let password = "";
  let error;
  import { stores, goto } from '@sapper/app';
  const { session } = stores();
  const login = async () =>　{
    if(!/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/.test(phone)) {
      error = "请输入正确的手机号码";
      return;
    }
    if(password.length<6) {
      error = "请输入6位以上的密码";
      return;
    }
    const response = await fetch("/api2/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({ phone, password }),
    });
    const parsed = await response.json();
    if (parsed.success == 0) {
      error = parsed.message;
    } else {
      $session.token = parsed.token;
      $session.user = parsed.user;
      await goto("/");
    }
  }
</script>
<svelte:head>
  <title>登录</title>
</svelte:head>
<div class="panel-header panel-header-sm" />
<div class="content">
  <div class="row">
    <div class="col-md-8 mx-auto">
      <div class="card">
        <div class="card-header">
          <h5 class="title">登录</h5>
        </div>
        <div class="card-body">
          {#if error}
            <div class="row">
              <div class="col-md-12">
                <p class="text-danger">{error}</p>
              </div>
            </div>
          {/if}
          <form on:submit|preventDefault="{login}" method="post">
            <div class="row">
              <div class="col-md-12">
                <div class="form-group">
                  <label for="phone">登录手机号</label>
                  <input
                    type="text"
                    id="phone"
                    class="form-control"
                    placeholder="您的手机号"
                    bind:value={phone} />
                </div>
              </div>
            </div>
            <div class="row">
              <div class="col-md-12">
                <div class="form-group">
                  <label for="password">登录密码</label>
                  <input
                    bind:value={password}
                    type="password"
                    id="password"
                    class="form-control"
                    placeholder="您的密码"/>
                </div>
              </div>
            </div>
            <div class="row">
              <div class="col-md-12">
                <div class="form-group">
                  <button type="submit" class="btn btn-primary">提交登录</button>
                  <!-- <a class="btn btn-neutral" href="/reg">注册</a> -->
                </div>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>